package cn.shujuhai.common.pluging.file;

import cn.hutool.core.util.IdUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @Author: zhangDeZhong
 * @Date: 2024/12/6 10:51
 * @Description: 上传下载文件工具类
 **/

public class FilesUtils {


    /**
     * 上传文件到指定文件夹
     *
     * @param file      上传的文件
     * @param uploadDir 上传的指定文件夹
     * @param viewUrl   浏览下载路径
     * @return 文件访问路径
     */
    public static String uploadFile(MultipartFile file, String uploadDir, String viewUrl) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        try {
            String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
            String uniqueFileName = IdUtil.fastSimpleUUID() + "_" + fileName;
            Path targetLocation = Paths.get(uploadDir, uniqueFileName);
            if (Files.notExists(targetLocation.getParent())) {
                Files.createDirectories(targetLocation.getParent());
            }
            Files.write(targetLocation, file.getBytes());
            return viewUrl + uniqueFileName;
        } catch (IOException ex) {
            throw new RuntimeException("文件上传失败", ex);
        }
    }

    /**
     * 上传文件到指定文件夹
     *
     * @param file      上传动态表单的文件
     * @param uploadDir 上传的指定文件夹
     * @param viewUrl   浏览下载路径
     * @return 文件访问路径
     */
    public static String uploadFormFile(MultipartFile file, String uploadDir, String viewUrl, Long formId) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        try {
            String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
            String uniqueFileName = IdUtil.fastSimpleUUID() + "_" + fileName;
            Path targetLocation = Paths.get(uploadDir, formId.toString(), uniqueFileName);
            if (Files.notExists(targetLocation.getParent())) {
                Files.createDirectories(targetLocation.getParent());
            }
            Files.write(targetLocation, file.getBytes());
            return Paths.get(viewUrl, formId.toString(), uniqueFileName).toString();
        } catch (IOException ex) {
            throw new RuntimeException("文件上传失败", ex);
        }
    }

}
